import { ConvertOptions } from '../types';

// 全局状态
let currentFile: File | null = null;
let currentCsvData: string = '';
let currentTheme: string = 'light';

// DOM元素
const elements = {
  uploadArea: document.getElementById('uploadArea') as HTMLDivElement,
  fileInput: document.getElementById('fileInput') as HTMLInputElement,
  fileInfo: document.getElementById('fileInfo') as HTMLDivElement,
  fileName: document.getElementById('fileName') as HTMLHeadingElement,
  fileSize: document.getElementById('fileSize') as HTMLSpanElement,
  fileType: document.getElementById('fileType') as HTMLSpanElement,
  previewContainer: document.getElementById('previewContainer') as HTMLDivElement,
  previewTable: document.getElementById('previewTable') as HTMLTableElement,
  previewStats: document.getElementById('previewStats') as HTMLSpanElement,
  toolbar: document.getElementById('toolbar') as HTMLDivElement,
  convertBtn: document.getElementById('convertBtn') as HTMLButtonElement,
  clearBtn: document.getElementById('clearBtn') as HTMLButtonElement,
  progressContainer: document.getElementById('progressContainer') as HTMLDivElement,
  progressText: document.getElementById('progressText') as HTMLParagraphElement,
  statusMessage: document.getElementById('statusMessage') as HTMLDivElement,
  encodingSelect: document.getElementById('encoding') as HTMLSelectElement,
  delimiterSelect: document.getElementById('delimiter') as HTMLSelectElement,
  sheetNameInput: document.getElementById('sheetName') as HTMLInputElement,
  hasHeaderCheckbox: document.getElementById('hasHeader') as HTMLInputElement,
  themeToggle: document.getElementById('themeToggle') as HTMLButtonElement,
  headerThemeToggle: document.getElementById('headerThemeToggle') as HTMLButtonElement
};

// 检查所有DOM元素是否成功加载
console.log('Checking DOM elements:');
Object.entries(elements).forEach(([key, element]) => {
  console.log(`${key}:`, element ? 'Found' : 'NOT FOUND');
});

// 初始化应用
function initializeApp(): void {
  console.log('Initializing app...');
  console.log('Upload area element:', elements.uploadArea);
  console.log('File input element:', elements.fileInput);
  
  setupEventListeners();
  loadThemePreference();
  updateThemeUI();
  
  console.log('App initialized successfully');
}

// 设置事件监听器
function setupEventListeners(): void {
  // 文件上传区域点击事件 - 简化逻辑
  elements.uploadArea.addEventListener('click', () => {
    console.log('Upload area clicked');
    elements.fileInput.click();
  });

  // 文件选择变化事件
  elements.fileInput.addEventListener('change', (event) => {
    console.log('File input changed', event);
    handleFileSelect(event);
  });

  // 拖拽事件
  elements.uploadArea.addEventListener('dragover', handleDragOver);
  elements.uploadArea.addEventListener('dragleave', handleDragLeave);
  elements.uploadArea.addEventListener('drop', handleDrop);

  // 转换按钮点击事件
  elements.convertBtn.addEventListener('click', handleConvert);

  // 清除按钮点击事件
  elements.clearBtn.addEventListener('click', clearFile);

  // 主题切换事件
  elements.themeToggle.addEventListener('click', toggleTheme);
  elements.headerThemeToggle.addEventListener('click', toggleTheme);
}

// 处理文件选择
async function handleFileSelect(event: Event): Promise<void> {
  const input = event.target as HTMLInputElement;
  if (input.files && input.files.length > 0) {
    await processSelectedFile(input.files[0]);
  }
}

// 处理拖拽悬停
function handleDragOver(event: DragEvent): void {
  event.preventDefault();
  elements.uploadArea.classList.add('dragover');
}

// 处理拖拽离开
function handleDragLeave(event: DragEvent): void {
  event.preventDefault();
  elements.uploadArea.classList.remove('dragover');
}

// 处理拖拽放置
async function handleDrop(event: DragEvent): Promise<void> {
  event.preventDefault();
  elements.uploadArea.classList.remove('dragover');

  if (event.dataTransfer && event.dataTransfer.files.length > 0) {
    const file = event.dataTransfer.files[0];
    if (file.name.toLowerCase().endsWith('.csv')) {
      await processSelectedFile(file);
    } else {
      showStatus('请选择CSV文件', 'error');
    }
  }
}

// 处理选中的文件
async function processSelectedFile(file: File): Promise<void> {
  try {
    currentFile = file;
    
    // 显示文件信息
    showFileInfo(file);
    
    // 读取文件内容
    const fileContent = await readFileContent(file);
    currentCsvData = fileContent;
    
    // 获取预览数据
    await showPreviewData();
    
    // 显示工具栏
    elements.toolbar.style.display = 'flex';
    
    showStatus('文件加载成功', 'success');
    
  } catch (error) {
    console.error('文件处理错误:', error);
    showStatus('文件读取失败', 'error');
    clearFile();
  }
}

// 读取文件内容
function readFileContent(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    
    reader.onload = (event) => {
      if (event.target && typeof event.target.result === 'string') {
        resolve(event.target.result);
      } else {
        reject(new Error('无法读取文件内容'));
      }
    };
    
    reader.onerror = () => {
      reject(new Error('文件读取错误'));
    };
    
    // 根据选择的编码读取文件
    const encoding = elements.encodingSelect.value;
    if (encoding === 'UTF-8') {
      reader.readAsText(file, 'utf-8');
    } else {
      reader.readAsText(file, 'gbk');
    }
  });
}

// 显示文件信息
function showFileInfo(file: File): void {
  elements.fileName.textContent = file.name;
  elements.fileSize.textContent = formatFileSize(file.size);
  elements.fileType.textContent = 'CSV';
  elements.fileInfo.style.display = 'block';
}

// 格式化文件大小
function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 B';
  
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 显示预览数据
async function showPreviewData(): Promise<void> {
  try {
    const options = getConvertOptions();
    
    // 调用主进程获取预览数据
    const result = await window.electronAPI.getCsvPreview(currentCsvData, options);
    
    if (result.success) {
      renderPreviewTable(result.data);
      elements.previewContainer.style.display = 'block';
    } else {
      throw new Error(result.error);
    }
  } catch (error) {
    console.error('预览数据获取失败:', error);
    showStatus('预览数据生成失败', 'error');
  }
}

// 渲染预览表格
function renderPreviewTable(data: any[][]): void {
  // 清空现有表格内容
  elements.previewTable.innerHTML = '';
  
  if (!data || data.length === 0) {
    return;
  }
  
  // 更新统计信息
  const totalRows = data.length - 1; // 减去表头行
  const totalColumns = data[0].length;
  const previewStats = document.getElementById('previewStats');
  if (previewStats) {
    previewStats.textContent = `${totalRows} 行 × ${totalColumns} 列 (显示前10行)`;
  }
  
  // 创建表头
  const thead = document.createElement('thead');
  const headerRow = document.createElement('tr');
  
  const headers = data[0];
  headers.forEach((header: any, index: number) => {
    const th = document.createElement('th');
    th.textContent = header || `列 ${index + 1}`;
    headerRow.appendChild(th);
  });
  
  thead.appendChild(headerRow);
  elements.previewTable.appendChild(thead);
  
  // 创建表格主体
  const tbody = document.createElement('tbody');
  
  // 显示前10行数据
  const displayData = data.slice(1, 11);
  displayData.forEach((row: any[]) => {
    const tr = document.createElement('tr');
    
    row.forEach((cell: any) => {
      const td = document.createElement('td');
      // 处理空值，显示占位符
      if (cell === null || cell === undefined || cell === '') {
        td.textContent = '-';
        td.style.color = 'var(--text-muted)';
        td.style.fontStyle = 'italic';
      } else {
        td.textContent = cell.toString();
      }
      tr.appendChild(td);
    });
    
    tbody.appendChild(tr);
  });
  
  elements.previewTable.appendChild(tbody);
  
  // 如果数据超过10行，添加提示行
  if (data.length > 11) {
    const moreRow = document.createElement('tr');
    const moreCell = document.createElement('td');
    moreCell.colSpan = totalColumns;
    moreCell.textContent = `... 还有 ${data.length - 11} 行数据未显示`;
    moreCell.style.textAlign = 'center';
    moreCell.style.color = 'var(--text-muted)';
    moreCell.style.fontStyle = 'italic';
    moreCell.style.padding = '1rem';
    moreRow.appendChild(moreCell);
    tbody.appendChild(moreRow);
  }
}

// 获取转换选项
function getConvertOptions(): ConvertOptions {
  return {
    encoding: elements.encodingSelect.value,
    delimiter: elements.delimiterSelect.value,
    sheetName: elements.sheetNameInput.value,
    hasHeader: elements.hasHeaderCheckbox.checked
  };
}

// 处理转换操作
async function handleConvert(): Promise<void> {
  if (!currentCsvData) {
    showStatus('请先选择CSV文件', 'warning');
    return;
  }
  
  try {
    // 显示进度指示器
    showProgress('正在转换...');
    
    // 获取转换选项
    const options = getConvertOptions();
    
    // 调用主进程进行转换
    const result = await window.electronAPI.convertCsvToXlsx(currentCsvData, options);
    
    if (result.success) {
      // 保存转换后的文件
      const defaultFileName = currentFile ? 
        currentFile.name.replace('.csv', '.xlsx') : 'converted.xlsx';
      
      const saveResult = await window.electronAPI.saveFileDialog(result.data, defaultFileName);
      
      if (saveResult.success) {
        showStatus(`转换成功！文件已保存至: ${saveResult.path}`, 'success');
      } else {
        throw new Error(saveResult.error);
      }
    } else {
      throw new Error(result.error);
    }
    
  } catch (error) {
    console.error('转换错误:', error);
    const errorMessage = error instanceof Error ? error.message : '未知错误';
    showStatus(`转换失败: ${errorMessage}`, 'error');
  } finally {
    hideProgress();
  }
}

// 显示进度指示器
function showProgress(message: string): void {
  elements.progressText.textContent = message;
  elements.progressContainer.style.display = 'block';
  elements.convertBtn.disabled = true;
}

// 隐藏进度指示器
function hideProgress(): void {
  elements.progressContainer.style.display = 'none';
  elements.convertBtn.disabled = false;
}

// 显示状态消息
function showStatus(message: string, type: 'success' | 'error' | 'warning'): void {
  elements.statusMessage.textContent = message;
  elements.statusMessage.className = `status-message status-${type}`;
  elements.statusMessage.style.display = 'block';
  
  // 5秒后自动隐藏
  setTimeout(() => {
    elements.statusMessage.style.display = 'none';
  }, 5000);
}

// 清除文件
function clearFile(): void {
  currentFile = null;
  currentCsvData = '';
  
  // 重置UI
  elements.fileInfo.style.display = 'none';
  elements.previewContainer.style.display = 'none';
  elements.toolbar.style.display = 'none';
  elements.fileInput.value = '';
  
  showStatus('文件已清除', 'success');
}

// 主题相关功能
function loadThemePreference(): void {
  const savedTheme = localStorage.getItem('theme');
  currentTheme = savedTheme || 'light';
}

function saveThemePreference(): void {
  localStorage.setItem('theme', currentTheme);
}

function toggleTheme(): void {
  currentTheme = currentTheme === 'light' ? 'dark' : 'light';
  saveThemePreference();
  updateThemeUI();
}

function updateThemeUI(): void {
  document.documentElement.setAttribute('data-theme', currentTheme);
  
  // 更新主题切换按钮图标
  const themeIcon = currentTheme === 'light' ? '🌙' : '☀️';
  elements.headerThemeToggle.innerHTML = `<span>${themeIcon}</span>`;
  elements.themeToggle.innerHTML = `<span>${currentTheme === 'light' ? '切换到暗色主题' : '切换到亮色主题'}</span>`;
}

// 初始化应用
document.addEventListener('DOMContentLoaded', initializeApp);